package com.example.gamestore.controller;

import com.example.gamestore.pojo.Review;
import com.example.gamestore.service.GameService;
import com.example.gamestore.service.ReviewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class ReviewController {

    @Autowired
    private ReviewService reviewService;

    @Autowired
    private GameService gameService;

    @PostMapping("/review/add")
    public Map<String, Object> addReview(@RequestBody Review review) {
        Map<String, Object> result = new HashMap<>();
        // 检查 game_id 是否存在
        if (gameService.getGameById(review.getGameId()) == null) {
            result.put("success", false);
            result.put("message", "你选择的游戏不存在，请重新选择");
            return result;
        }

        Review addedReview = reviewService.add(review);
        if (addedReview != null) {
            result.put("success", true);
            result.put("message", "评论添加成功");
        } else {
            result.put("success", false);
            result.put("message", "评论添加失败，请重试");
        }
        return result;
    }

    @GetMapping("/queryAll")
    public List<Review> queryAllReviews() {
        return reviewService.queryAll();
    }

    @GetMapping("/queryById/{id}")
    public Review queryReviewById(@PathVariable Long id) {
        return reviewService.queryById(id);
    }

    // 新增更新接口
    @PutMapping("/update")
    public String updateReview(@RequestBody Review review) {
        int result = reviewService.updateReview(review);
        if (result > 0) {
            return "更新成功";
        } else {
            return "更新失败";
        }
    }

    @DeleteMapping("/review/delete/{id}")
    public String deleteReview(@PathVariable Long id) {
        int result = reviewService.delete(id);
        if (result > 0) {
            return "删除成功";
        } else {
            return "删除失败";
        }
    }

    // 根据游戏 ID 查询评论
    @GetMapping("/queryByGameId/{gameId}")
    public List<Review> queryReviewsByGameId(@PathVariable Long gameId) {
        return reviewService.queryByGameId(gameId);
    }
}